package com.keguoyu.easymvp.ioc.internal

import com.android.builder.model.AndroidProject
import com.keguoyu.easymvp.ioc.internal.util.GSON
import org.apache.commons.io.FileUtils
import org.gradle.api.Project
import java.io.File
import java.io.FileReader
import java.io.FileWriter

class InvokerCache {
  private val mFile: File;

  constructor(path: String) {
    mFile = File(path)
  }

  fun compareAndSaveInvokerInfos(infos: InvokerInfos): Boolean {
    val lastInfo = read()
    lastInfo?.init()
    lastInfo?.mCacheInfo?.init()
    val changed = !infos.equals(lastInfo)
    write(infos)
    return changed
  }

  private fun write(model: InvokerInfos) {
    if (!mFile.exists()) {
      FileUtils.forceMkdir(mFile.parentFile)
      mFile.createNewFile()
    }
    val writer = FileWriter(mFile)
    GSON.toJson(model, writer)
    writer.flush()
    writer.close()
  }

  private fun read(): InvokerInfos? {
    if (!mFile.exists()) {
      return null
    }
    val reader = FileReader(mFile)
    return GSON.fromJson(reader, InvokerInfos::class.java)
  }
}

object CacheUtils {
  fun getCachePath(project: Project) = "${project.buildDir.absolutePath}/" +
      "${AndroidProject.FD_INTERMEDIATES}/" +
      "invoker/cachedInfo.json"
}